package ie.live.byrnep.pleasesleephere.base;

import ie.live.byrnep.pleasesleephere.R;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;



import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;

public class CloudConnection {
	
	private Json json = new Json();
	private String generateRoomUrl;
	private String generateRoomGpsUrl;
	private String thumbNailImageUrl;
	private String roomRequestUrl;
	private final String LOCATION_KEY="location";
	private final String ROOM_KEY="roomKey";
	private JSONObject jsonObj = null;
	private JSONArray array;
	private String roomDetails;
	private static boolean connectSet=false;
	private List<HashMap<String, Object>> aList = new ArrayList<HashMap<String, Object>>();
	private Map<String, Object> roomMap = new HashMap<String, Object>();
	
	public CloudConnection(Context c) {
		this.generateRoomUrl = c.getString(R.string.generate_rooms_url);
		this.generateRoomGpsUrl = c.getString(R.string.generate_rooms_gps_url);
		this.roomRequestUrl = c.getString(R.string.send_message_url);
	}

	private String connectToCloud(final String stringUrl,
		final JSONObject jsonObjSend) {
		String sentMessage=null, receivedMessage = null;


		try {
			URL url =  new URL(stringUrl);
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			sentMessage = jsonObjSend.toString();

			final OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
			osw.write(sentMessage);
			osw.flush();
			osw.close();
			
			if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
				receivedMessage = readStream(connection.getInputStream());			
			}

			connection.disconnect();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return receivedMessage;
	}
	
	
	private String readStream(InputStream in) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(in));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}


	public String checkForLocation(final String searchValue) {
		String urlKeyString;
		jsonObj = json.encodeString(LOCATION_KEY, searchValue);
		urlKeyString = connectToCloud(generateRoomUrl, jsonObj);
		if (urlKeyString.equals("[]\n"))
			urlKeyString = null;
		return urlKeyString;
		
	}
	public String checkLocationFromGps(final String latitude, final String longitude,final  int distanceChoice) {
		String urlKeyString;
		jsonObj = json.encodeLocCord(latitude, longitude, distanceChoice);
		urlKeyString = connectToCloud(generateRoomGpsUrl, jsonObj);
		if (urlKeyString.equals("[]\n"))
			urlKeyString = null;
		return urlKeyString;
	}

	@SuppressWarnings("unchecked")
	public List<HashMap<String, Object>> retrieveListItems(final String urlKeyString) {
		
		array = json.getUrlArray(urlKeyString);
		Iterator<String> iterator = array.iterator();
		
		while (iterator.hasNext()) {
			String stringKey = iterator.next();

			jsonObj = json.encodeString(ROOM_KEY,stringKey);
			roomDetails = connectToCloud(generateRoomUrl, jsonObj);
			aList.add(json.getHashMap(roomDetails,stringKey, generateRoomUrl,thumbNailImageUrl));
		}
		return aList;
	}

	public Map<String, Object> getRoomMap(String entityKey) {
		jsonObj = json.encodeString(ROOM_KEY,entityKey);
		roomDetails = connectToCloud(generateRoomUrl, jsonObj);
		roomMap = json.getRoomMap(roomDetails,thumbNailImageUrl);
		return roomMap;
	}

	public void setThumbnailImg(final ImageView imageView, final String entityKey) {
		
		jsonObj = json.encodeString(ROOM_KEY,entityKey);
		ImageDownloader downloadTask = new ImageDownloader();
		

		/** Starting the task created above */
		downloadTask.download(generateRoomUrl, imageView,jsonObj);
	}

	public boolean sendRoomRequest(final MessageDetails messageDetails) {
		jsonObj = json.encodeRoomRequestMessage(messageDetails);
		String success = connectToCloud(roomRequestUrl, jsonObj);
		if (success == "200\n")
			return true;
		else		
			return false;
	}
}
